package com.yantong.quartz.job;

import com.yantong.enums.GroupTypeEnum;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.OrderProductDetailVo;
import com.yantong.pojo.vo.SpellGroupOrdVo;
import com.yantong.quartz.job.manage.OrderTimerManage;
import com.yantong.service.*;
import com.yantong.utils.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单任务执行类
 *
 * @author kanghaixin
 * @date 2018/9/22.10:03
 */

@Service
public class OrderTimer {
	private static Logger logger = LoggerFactory.getLogger(OrderTimer.class);
	@Autowired
	private ConfigService configService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private CentreService centreService;
	@Autowired
	private ProductService productService;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private PayService payService;
	@Autowired
	private MarketingGroupService marketingGroupService;
	@Autowired
	private OrderTimerManage orderTimerManage;

	private boolean taskOn = true;


	@Scheduled(cron = "0 5 21 * * ?")
	public void autoUpdateCart() {
		if (!taskOn) {
			logger.info("system task set off!autoDelivery!");
			return;
		}
		productService.autoUpdateCart();
	}

//	/**
//	 * 自动确认收货  每日凌晨2点执行一次
//	 */
//	@Scheduled(cron = "0 0 11 * * ?")
//	public void autoDelivery() {
//		if (!taskOn) {
//			logger.info("system task set off!autoDelivery!");
//			return;
//		}
//		logger.info("auto check order delivery start...");
//		List<Centre> list = centreService.listAllCentres();
//		if (CollectionUtils.isEmpty(list)) {
//			logger.info("not found centre info! auto check order delivery end...");
//			return;
//		}
//		for (Centre centre : list) {
//			/**获取系统自动确认收货设置**/
//			int hour = 24;
//			TradeConfig config = configService.getTradeConfig(centre.getCentreId());
//			if (config != null) {
//				hour = config.getAutoReceiveDays() == null ? 24 : config.getAutoReceiveDays();
//			}
//			/**设置状态为已发货，且未收货，且发货时间已超过*小时的订单未已收货**/
//			Date targetDate = DateUtils.getAddHourDate(new Date(), -hour);
//			while (true) {
//
//				List<OrderProduct> ops = orderService.getCanDeliveryOps(targetDate, centre.getCentreId(), 0, 200);
//				if (CollectionUtils.isEmpty(ops)) {
//					logger.info("商户:{}, 自动确认收货完成", centre.getName());
//					break;
//				}
//				KdniaoUtil kdniaoUtil = new KdniaoUtil();
//
//				for (OrderProduct op : ops) {
//					if (op.getIsKuaidi() == 1 && StringUtils.isNotEmpty(op.getExpressCode())) {
//
//						String result = kdniaoUtil.getOrderTracesByJson(op.getExpressCode(), op.getKuaidisn());
//						if (!result.contains("\"State\" : \"3\"")) {
//							Order o = new Order();
//							o.setSendTime(new Date());
//							o.setId(op.getOrderid());
//							orderService.update(o);
//							continue;
//						}
//
//					}
//					if (op == null) {
//						continue;
//					}
//					try {
//						//给分公司和代理计算佣金，插入佣金表
//						orderService.autoProfitToBOA(op, centre.getCentreId());
//
//						Order order = orderService.getByKey(op.getOrderid());
//						//订单角色分佣
//
//
//					} catch (Exception e) {
//						e.printStackTrace();
//						logger.error("给分公司和代理计算佣金利益报错");
//					}
//					OrderProduct uop = new OrderProduct();
//					uop.setId(op.getId());
//					uop.setStatus(OrderStatus.delivery_success.getCode());
//					orderService.updateOrderProduct(uop);
//					if (op.getOrderStatus() < OrderStatus.delivery_success.getCode()) {
//						Order o = new Order();
//						o.setFetchTime(new Date());
//
//						o.setStatus(OrderStatus.delivery_success.getCode());
//						o.setId(op.getOrderid());
//						orderService.update(o);
//					}
//
//					/**商户结算**/
//					centreService.saveAmountLog(op.getId(), centre.getCentreId(), op, op.getOrdersn());
//
//
//				}
//
//				//获取订单商品集合中筛选出订单id去重
//				List<Long> orderNoList = ops.stream().map(OrderProduct::getOrderid).distinct().collect(Collectors.toList());
//				for (Long orderId : orderNoList) {
//
//					Order order = orderService.getByKey(orderId);
//
//					//拼团订单一二级推荐人分佣
//					if (order.getOrderType() == ProductType.Spellgroup.getType()) {
//						payService.marketingGroupCommission(order);
//					}
//
//					List<OrderProduct> orderProductList = orderProductMapper.getByOrderId(orderId);
//					//赠送积分
//					if(orderProductList != null){
//						for(OrderProduct orderProduct:orderProductList){
//							memberIntegralService.addMemberIntegral(order.getMid(), new BigDecimal(orderProduct.getCredit()), order.getId(), "购买"+orderProduct.getProductName()+"赠送");
//						}
//					}
//
//					//查询该笔订单使用过的站点优惠券的总金额
//					String ticketAmt = ticketRecordMapper.sumTicketByOrderId(orderId);
//					if (!org.springframework.util.StringUtils.isEmpty(ticketAmt) && !ticketAmt.equals("0")) {
//						CentreAmount centreAmount = centreAmountMapper.getByKey(order.getCentreId());
//						//结算下一笔订单
//						AmountLog al = new AmountLog();
//						al.setOrderId(order.getId());
//						al.setCentreId(centre.getCentreId());
//						al.setOrderSn(order.getOrdersn());
//						al.setMoney(new BigDecimal("-" + ticketAmt));//扣减
//						al.setFlowType(11);//站点结算扣除优惠券金额
//						al.setRemark("订单平台结算给站点扣除优惠券金额：" + ticketAmt + " 订单号:" + order.getOrdersn() + "【变动金额" + centreAmount.getAmount() + "->" + centreAmount.getAmount().subtract(new BigDecimal(ticketAmt)) + "】");
//						al.setBeforeamount(centreAmount.getAmount());
//						al.setAfteramount(centreAmount.getAmount().subtract(new BigDecimal(ticketAmt)));
//
//						amountLogMapper.saveAmountLog(al);
//						centreAmountMapper.deductAmount(order.getCentreId(), new BigDecimal(ticketAmt));
//
//					}
//
//
//				}
//
//			}
//		}
//		logger.info("auto check order delivery end...");
//	}


	/**
	 * 完成订单，每日凌晨3点执行
	 */
	@Scheduled(cron = "0 0/30 7 * * ?")
	//@Scheduled(cron = "0 0/5 * * * ?")
	public void completedOrder() {
		if (!taskOn) {
			logger.info("system task set off!completedOrder!");
			return;
		}
		logger.info("complete order start...");
		int days = 0;
		List<Centre> centres = centreService.listAllCentres();
		if (CollectionUtils.isEmpty(centres)) {
			logger.info("not found centre info! auto completedOrder end...");
			return;
		}
		double exchange = 100d;
		for (Centre centre : centres) {
			TradeConfig config = configService.getTradeConfig(centre.getCentreId());
			if (config != null && config.getExchangeIntegral() != null) {
				exchange = config.getExchangeIntegral();
			}
			if (config != null) {
				days = config.getAutoCompletedOrder() == null ? 0 : config.getAutoCompletedOrder();
			}
			int index = 1, size = 200;
			while (true) {
				List<Order> list = orderService.listSuccessOrders(DateUtils.getDateStartTime(DateUtils.getAddDayDate(new Date(), -days)), DateUtils.parseDate("2018-11-26"),
						centre.getCentreId(), (index - 1) * size, size);
				if (CollectionUtils.isEmpty(list)) {
					break;
				}
				for (Order o : list) {
					logger.info("完成订单：{}", o.getOrdersn());
					/**获取未取消，订单商品**/
					List<OrderProduct> ops = orderService.listOrderProducts(o.getId(), o.getStatus(), 0);
					if (CollectionUtils.isNotEmpty(ops)) {
						orderService.autoCompleteOrder(ops, centre.getCentreId(), exchange);
					}

					orderService.completeOrder(o);
				}
			}
		}
		logger.info("complete order end...");
	}


	/**
	 * 计算商品佣金
	 *
	 * @param op
	 * @return
	 */
	public BigDecimal calcCommission(OrderProduct op) {
		if (op == null) {
			return null;
		}
		Integer type = op.getHeadtype();
		BigDecimal commission = op.getHeadcommission();
		if (type == null || commission == null) {
			logger.info("headType or commission is null,orderId:{}", op.getOrderid());
			return null;
		}

		if (type == 0) {
			/**按金额计算**/
			return commission.multiply(new BigDecimal(op.getTotal())).setScale(2, BigDecimal.ROUND_HALF_UP);
		} else {
			/**按百分比**/
			return commission.multiply(op.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		}
	}



	/**
	 * 完成订单，每日凌晨3点执行
	 */
	@Scheduled(cron = "0 0/50 7 * * ?")
	//@Scheduled(cron = "0 0/7 * * * ?")
	public void completedExpressOrder() {
		if (!taskOn) {
			logger.info("system task set off!completedExpressOrder!");
			return;
		}
		logger.info("completedExpressOrder order start...");
		int days = 0;
		List<Centre> centres = centreService.listAllCentres();
		if (CollectionUtils.isEmpty(centres)) {
			logger.info("not found centre info! auto completedExpressOrder end...");
			return;
		}
		double exchange = 100d;
		for (Centre centre : centres) {
			TradeConfig config = configService.getTradeConfig(centre.getCentreId());
			if (config != null && config.getExchangeIntegral() != null) {
				exchange = config.getExchangeIntegral();
			}
			if (config != null) {
				days = config.getAutoCompletedExpressOrder() == null ? 1 : config.getAutoCompletedExpressOrder();
			}
			/**获取未取消，订单商品**/
			List<OrderProduct> ops = orderService.listSuccessOrderProductsTime(DateUtils.getDateStartTime(DateUtils.getAddDayDate(new Date(), -days)), DateUtils.parseDate("2018-11-26"),
					centre.getCentreId());
			if (CollectionUtils.isNotEmpty(ops)) {
				orderService.autoCompleteOrder(ops, centre.getCentreId(), exchange);
			}
		}
		logger.info("complete order end...");

	}

	/**
	 * 拼团订单 每隔两小时跑一次 每隔5个小时跑一次
	 */
	@Scheduled(cron = "0 0 */5 * * ?")
	public void completedSpellGroupOrder() {
		if (!taskOn) {
			logger.info("system task set off!autoDelivery!");
			return;
		}
		logger.info("拼团跑跑进来==============");
		//发起人拼团中的订单
		List<OrderProductDetailVo> list = orderService.getTaskSpellGroupOrd();
		if (CollectionUtils.isNotEmpty(list)) {
			for (OrderProductDetailVo ord : list) {
				//查询到商品
				//ProductCentre product = productCentreMapper.selectByPrimaryKey(ord.getProductId());
				MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(ord.getActivityId());
				if (marketingGroup != null) {
					//如果现在的时间小于下架时间才可以修改拼团状态
					//if (new Date().compareTo(marketingGroup.getEndTime()) == -1) {
					//订单拼团人数加商家设置已拼团人数大于等于商品拼团人数
					boolean bol = false;
					if(GroupTypeEnum.RANDOM.getCode().equals(marketingGroup.getType())){
						bol = (marketingGroup.getNeedJoinGroupNum() - marketingGroup.getAddNumber()) <= ord.getPeoplenum();
					}else if(GroupTypeEnum.SNAP_UP.getCode().equals(marketingGroup.getType())){
						bol = marketingGroup.getNeedJoinGroupNum() <= ord.getPeoplenum();
					}
					if (bol) {
						if (GroupTypeEnum.RANDOM.getCode().equals(marketingGroup.getType())) {
							//改成已拼团成功
							SpellGroupOrdVo vo = new SpellGroupOrdVo();
							vo.setSgorderId(ord.getId());
							List<Order> ords = orderMapper.getOrderByStu(vo);
							for (Order order : ords) {
								SpellGroupOrdVo spellGroupOrdVo = new SpellGroupOrdVo();
								spellGroupOrdVo.setOrderid(order.getId());
								spellGroupOrdVo.setSpellgroupStu(2);
								//修改订单商品拼团状态
								orderProductMapper.updSpellgroupStu(spellGroupOrdVo);
							}
							//修改订单拼团成功
							orderMapper.updateSpellGroupOrdStu(vo);
						}else{
							Order sgOrder = orderService.getByKey(ord.getId());
							payService.marketingSnapUpDispose(marketingGroup,sgOrder);
						}
					} else if (new Date().compareTo(marketingGroup.getEndTime()) == 1) {
						//订单拼团人数加商家设置已拼团人数小于商品拼团人数
						if ((marketingGroup.getNeedJoinGroupNum() - marketingGroup.getAddNumber()) > ord.getPeoplenum()) {
							SpellGroupOrdVo vo = new SpellGroupOrdVo();
							vo.setSgorderId(ord.getId());
							List<Order> ords = orderMapper.getOrderByStu(vo);
							for (Order order : ords) {
								//退款
								orderService.cancelOrder(order.getId(), 1);
							}
						}
					}

				} else {
					continue;
				}
			}
		}
		logger.info("拼团跑跑结束==============");
	}

	/**
	 * 每天凌晨一点 统一定时任务
	 */
	@Scheduled(cron = "0 0 1 * * ?")
	public void everyDayoneVClock(){
		//聚合支付订单  每天凌晨一点结算
		orderTimerManage.juheOrderSplitSettlement();
	}


}